package com.bit.book.interceptor;

import com.bit.book.constant.Constants;
import com.bit.book.entity.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("执行preHandle 方法");
        response.setContentType("application/json;charset=utf-8");
        //true 放行   false- 拦截
        //判断用户是否登录
        HttpSession session = request.getSession(false);
        if (session!=null &&  StringUtils.hasLength((String)session.getAttribute(Constants.SESSION_USER_NAME))){
            //用户登录
            log.info("用户已登录");
            return true;
        }
        //用户未登录
        log.warn("用户未登录");
        Result result = Result.unlogin();
        response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
        response.setStatus(401); //http 状态码
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("执行 postHandle 方法");
    }
}
